from app.db.mongoClient import ErrMongoClient, get_mongo_client
from . import dbSynPosDishes, collectionDishList


def check_dishes(diningNo, stallNo, dishIds):
    '''
    菜品审核
    "dishIds": [
        {
            "dishId": "菜品Id",
            "dishState": "未通过/通过/待审核（fail/pass/stay）",
            "checkFailDesc": "审核未通过描述（通过描述默认填写""）"
        }
    ]
    
    "newList": [
        {
            "dishId": "菜品Id",
            "dishName": "",
            "dishState": "未通过/通过/待审核（fail/pass/stay）",
            "checkFailDesc": "审核未通过描述（通过描述默认填写""）",
            "...": "..."
        }
    ]
    '''
    try:
        mg_client = get_mongo_client()
        collection = mg_client[dbSynPosDishes][collectionDishList]
        cond = {'diningNo': diningNo, 'stallNo':stallNo }
        res = collection.find_one(cond)
        if res is None:
            return None

        newList = res.get('dishList')
        if newList is None or len(newList) <= 0:
            return None

        for dish_dict in dishIds:
            dishId = dish_dict.get('dishId')
            if dishId is not None:
                for n, v in enumerate(newList):
                    if dishId == v.get('dishId'):
                        newList[n]['dishState'] = dish_dict.get('dishState')
                        newList[n]['checkFailDesc'] = dish_dict.get('checkFailDesc')
        
        return collection.find_one_and_update(cond, 
                            {'$set':                         
                                {'dishList': newList}                          
                            })
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def check_dishes_dishIds(dishState, checkFailDesc, dishIds):
    '''
    菜品审核
    {
        "dishState": "未通过/通过/待审核（fail/pass/stay）",	  // 必填字段，不可为空
        "checkFailDesc": "审核未通过描述（通过描述默认填写""）"    // 必填字段，可为空
        "dishIds": [         // 必填字段，不可为空
            {
                "diningNo": "餐厅Id", // 必填字段，不可为空
                "stallNo": "档口Id",  // 必填字段，不可为空
                "dishId": "菜品Id"   // 必填字段，不可为空			
            },
            {
                "diningNo": "餐厅Id", // 必填字段，不可为空
                "stallNo": "档口Id",  // 必填字段，不可为空
                "dishId": "菜品Id"   // 必填字段，不可为空
            }
        ]
    }
    '''
    try:
        mg_client = get_mongo_client()
        collection = mg_client[dbSynPosDishes][collectionDishList]
        update = {
            '$set': {
                'dishList.$.dishState': dishState,
                'dishList.$.checkFailDesc': checkFailDesc
            }
        }
        for v in dishIds:
            cond = {
                'diningNo': v.get('diningNo'),
                'stallNo': v.get('stallNo'),
                'dishList.dishId': v.get('dishId')
            }
            collection.find_one_and_update(cond, update)
        return None
    except Exception as e:
        raise ErrMongoClient.data(str(e))